# encoding: utf-8


"""

@author: tongzhenguo

@time: 2021/6/19 下午8:41

@desc:

自选股监控(机会、风险、每日估值报告)

模版：
xxxx/{行业}/{主营};
入选理由:{REASON};
PE-TTM{PE-TTM}(历史{percent}%),2020年度摊薄ROE{ROE},2021一季度同比扣非净利{CAGR}%,peg{PEG}%;
价格合理范围在{P1,P2,P3},pe分位点在{PP1,PP2,PP3}

"""
import pandas as pd

from app.stock_certificate_price import AppraisementCalculator
from app.stock_rank import StockRank
from const import PROJ_HOME, TRADE_CAL_FILE
from date_util import last_year, now_quarter, last_trade_date
from mongo_db import MongoDB


class SelfSelectStockMonitor(object):
    def __init__(self):
        # 自选股代码列表
        self.stock_list = pd.read_csv(PROJ_HOME + "/data/自选股/自选股.csv", dtype=str)["code"].to_list()
        self.db_name = "stock"
        self.collection_name = "stock"
        self.mongo_db = MongoDB(uri="mongodb://127.0.0.1:27017", database=self.db_name)
        # 年度财报时间
        self.year = int(last_year())
        # 季度财报时间
        self.quarter = int(now_quarter())
        # self.date = 20210611
        # 最近交易日时间，18点之后更新当日数据
        trade_cal_df = pd.read_csv(TRADE_CAL_FILE, dtype={"cal_date": str, "is_open": str})
        self.date = last_trade_date(trade_cal_df)

    def rank(self, sr, rank_fn, data):
        """自选股排名,rank_fn是stock_rank类中的排名方法"""
        # sr = StockRank()
        func = getattr(sr, rank_fn)
        # data = ss.points_evaluation_card(data, columns, bin_list, score_list)
        return func(data)

    def price(self, ac, price_fn, data):
        """自选股估值,price_fn是stock_certificate_price类中的估值方法"""
        data = getattr(ac, price_fn)(data)
        return data


if __name__ == "__main__":
    ss = SelfSelectStockMonitor()
    sr = StockRank()
    data1 = sr.make_points_evaluation_card_data()
    data1 = ss.rank(sr, "points_evaluation_card", data1)[
        ["_id", "2020年度-股票简称", f"{ss.date}日-滚动市盈率", f"{ss.date}日-市净率", f"{ss.year}年度-净资产收益率(%)"]]
    data = ss.mongo_db.fetch_data(ss.collection_name, {"_id": {"$in": ss.stock_list}}, ["_id"])
    calculator = AppraisementCalculator()

    data2 = data[["_id"]]
    for m, c in zip(calculator.price_methods, calculator.price_columns):
        tmp = ss.price(calculator, m, data)
        data2 = pd.merge(data2, tmp[["_id", c]], how="left", on="_id")

    data = pd.merge(data1, data2, how="left", on="_id")
    data.to_csv(PROJ_HOME + "/data/自选股报告/自选股报告.csv", index=False)
